<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="!dataFormData.id ? '新增' : '修改'"
    @closed="onDialogClosed"
  >
    <el-form
      ref="dataFormRef"
      :model="dataFormData"
      :rules="dataRule"
      label-width="120px"
    >
      <el-form-item
        label="内容"
        prop="content"
      >
        <el-input
          v-model="dataFormData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item
        label="类型"
        prop="type"
      >
        <el-select
          v-model="dataFormData.type"
          placeholder="请选择类型"
        >
          <el-option
            label="文本"
            value="text"
          />
          <el-option
            label="图片"
            value="image"
          />
          <el-option
            label="视频"
            value="video"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="dataFormData.type === 'image'"
        label="图片"
        prop="mediaContent"
      >
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
        >
          <img
            v-if="dataFormData.mediaContent"
            :src="dataFormData.mediaContent"
            class="avatar"
          >
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item
        v-if="dataFormData.type === 'video'"
        label="视频"
        prop="mediaContent"
      >
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleVideoSuccess"
          :before-upload="beforeVideoUpload"
        >
          <video
            v-if="dataFormData.mediaContent"
            :src="dataFormData.mediaContent"
            class="avatar"
            controls
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/utils/http'

const visible = ref(false)
const dataFormRef = ref(null)

const dataFormData = reactive({
  id: 0,
  content: '',
  type: 'text',
  mediaContent: '',
  status: 'pending'
})

const dataRule = reactive({
  content: [
    { required: true, message: '内容不能为空', trigger: ['blur', 'change'] }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  mediaContent: [
    { 
      required: true, 
      message: '请上传媒体内容', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (dataFormData.type !== 'text' && !value) {
          callback(new Error('请上传媒体内容'))
        } else {
          callback()
        }
      }
    }
  ]
})

const init = async (id) => {
  try {
    Object.assign(dataFormData, {
      id: 0,
      content: '',
      type: 'text',
      mediaContent: '',
      status: 'pending'
    })

    visible.value = true
    
    await nextTick()
    
    if (dataFormRef.value) {
      dataFormRef.value.resetFields()
    }

    if (id) {
      const { data } = await http({
        url: http.adornUrl(`/social/post/info/${id}`),
        method: 'get',
        params: http.adornParams()
      })
      
      if (data && data.code === '00000') {
        Object.assign(dataFormData, data.data)
      } else {
        throw new Error(data?.msg || '获取数据失败')
      }
    }
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error(error.message || '初始化失败')
    visible.value = false
  }
}

const emit = defineEmits(['refresh-data-list'])

const closeDialog = () => {
  visible.value = false
}

const onDialogClosed = () => {
  emit('refresh-data-list')
}

const dataFormSubmit = async () => {
  if (!dataFormRef.value) return
  
  try {
    await dataFormRef.value.validate()
    
    const { data } = await http({
      url: http.adornUrl(`/social/post/${!dataFormData.id ? 'save' : 'update'}`),
      method: 'post',
      data: http.adornData({
        id: dataFormData.id || undefined,
        content: dataFormData.content.trim(),
        type: dataFormData.type,
        mediaContent: dataFormData.mediaContent,
        status: dataFormData.status
      })
    })
    
    if (data && data.code === '00000') {
      ElMessage.success('操作成功')
      visible.value = false
      emit('refresh-data-list')
    } else {
      throw new Error(data?.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const uploadUrl = '/api/file/upload'

const handleImageSuccess = (res) => {
  if (res.code === '00000') {
    dataFormData.mediaContent = res.data
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }

  return isImage && isLt2M
}

const handleVideoSuccess = (res) => {
  if (res.code === '00000') {
    dataFormData.mediaContent = res.data
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
  }
  if (!isLt20M) {
    ElMessage.error('视频大小不能超过 20MB!')
  }

  return isVideo && isLt20M
}

defineExpose({
  init
})
</script>

<style scoped>
.el-link {
  font-size: 14px;
}

/* 如果上传组件确实需要这些样式，保留它们并添加使用的地方 */
.upload-container {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    
    &:hover {
      border-color: #409EFF;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 